package com.hicorp.segment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hicorp.segment.mapper.ReceiptsMapper;
import com.hicorp.segment.mapper.ReceiptsSubMapper;
import com.hicorp.segment.pojo.po.Material;
import com.hicorp.segment.pojo.po.MaterialConcrete;
import com.hicorp.segment.pojo.po.Receipts;
import com.hicorp.segment.pojo.po.ReceiptsSub;
import com.hicorp.segment.service.ReceiptsService;
import com.hicorp.segment.utils.ResultBean;
import com.hicorp.segment.utils.TableNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wqs
 * @version 1.0.1
 */
@Service("receiptsService")
@Slf4j
public class ReceiptsServiceImpl implements ReceiptsService {

    @Resource
    private ReceiptsMapper receiptsMapper;

    @Resource
    private ReceiptsSubMapper receiptsSubMapper;

    /**
     * 查询所有
     *
     * @param tableName 表名
     * @return 查询到的数据
     */
    @Override
    public ResultBean<List<Receipts>> queryInfo(String tableName) {
        Condition condition = new Condition(Receipts.class);
        condition.setTableName(TableNameUtil.replaceTableName(tableName));
        System.out.println(tableName);
        System.out.println(TableNameUtil.replaceTableName(tableName));
        condition.setOrderByClause("`no` asc");
        try {
            List<Receipts> receiptsList = receiptsMapper.selectByExample(condition);
            return new ResultBean<>(receiptsList);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultBean<>(400, "查询失败!");
        }
    }

    /**
     * 新增单据
     *
     * @param receipts 新增的数据.
     * @return 返回新增单据的主表的id.
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultBean<Long> createRecord(String tableName, Receipts receipts, String authorityCode) {
        receipts.setAuthorityCode(authorityCode);
        receipts.setTableName(TableNameUtil.replaceTableName(tableName));
        String subTableName = receipts.getTableName() + "_sub";

        receipts.setTableNameSub(subTableName);

        List<ReceiptsSub> receiptsSubList = new ArrayList<>();

        // 如果前端设置了, 在这里可以删除掉这个.
        if (receipts.getReceiptsSub() != null) {
            receipts.getReceiptsSub().forEach(receiptsSub -> receiptsSub.setTableName(subTableName));
            receiptsSubList = receipts.getReceiptsSub();
        }
        try {
            receiptsMapper.insertReceipts(receipts);
            if (receiptsSubList.size() > 0) {
                receiptsSubMapper.insertReceiptsSubList(subTableName, receiptsSubList);
            }
            return new ResultBean<>(receipts.getId(), 200, "新增成功!");
        } catch (Exception e) {
            log.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultBean<>(400, "新增失败!");
        }
    }

    /**
     * 修改单据
     *
     * @param receipts 修改的数据.
     * @return 修改的单据的主表id.
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultBean<Long> updateRecord(String tableName, Receipts receipts) {
        receipts.setTableName(TableNameUtil.replaceTableName(tableName));
        String subTableName = receipts.getTableName() + "_sub";

        List<ReceiptsSub> receiptsSubList = new ArrayList<>();

        // for循环，每个receiptsSub都加上表名.
        // 如果前端设置了, 在这里可以删除掉这个.
        if (receipts.getReceiptsSub() != null) {
            receipts.getReceiptsSub().forEach(receiptsSub -> receiptsSub.setTableName(receipts.getTableName() + "_sub")
            );
            receiptsSubList = receipts.getReceiptsSub();
        }
        try {
            receiptsSubMapper.batchDeleteRecord(receipts.getNo(), subTableName);
            receiptsMapper.updateReceipts(receipts);
            if (receiptsSubList.size() > 0) {
                receiptsSubMapper.insertReceiptsSubList(subTableName, receiptsSubList);
            }
            return new ResultBean<>(receipts.getId(), 200, "数据更新成功!");
        } catch (Exception e) {
            log.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultBean<>(400, "更新失败!");
        }
    }

    //批量删除
    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> batchDeleteRecord(String tableName, List<Long> ids) {
        try {
            System.out.println(tableName);
            System.out.println(TableNameUtil.replaceTableName(tableName));
            //for循环，每个receiptsSub都加上表名
            ids.forEach(id -> {
                String no = receiptsMapper.selectNoById(TableNameUtil.replaceTableName(tableName), id);
                receiptsSubMapper.batchDeleteRecord(no, TableNameUtil.replaceTableName(tableName) + "_sub");
            });
            Integer integer = receiptsMapper.batchDeleteRecord(ids, TableNameUtil.replaceTableName(tableName));
            return new ResultBean<>(integer);
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultBean<>(400, "删除失败!");
        }
    }

    //批量作废
    @Override
    @Transactional(rollbackFor = Exception.class)   //回滚
    public ResultBean<Integer> batchInvalidRecord(String tableName, List<Long> ids) {
        try {
            Integer integer = receiptsMapper.batchInvalidRecord(ids, TableNameUtil.replaceTableName(tableName));
            return new ResultBean<>(integer);
        } catch (Exception e) {
            log.error(e.getMessage());
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    //TODO 单据主表搜索，未实现
    @Override
    public Object selectRecords(String tableName, String fieldName, String fieldValue) {
        return null;
    }

    //生成单据内部编号
    @Override
    public ResultBean<String> generateReceiptsNo(String tableName, String preNo) {
        try {
            tableName = TableNameUtil.replaceTableName(tableName);
            String returnNO = receiptsMapper.generateReceiptsNo(tableName, preNo + "%");
            if (returnNO == null) {
                returnNO = preNo + "0001";
            } else {
                String str1 = "000" + (Integer.parseInt(returnNO.substring(12)) + 1);
                returnNO = preNo + str1.substring(str1.length() - 4);
            }
            return new ResultBean<>(returnNO);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultBean<>(400, "创建内部编号失败!");
        }
    }


    // 查询，通过表名和内部编码来获取主子表数据
    @Override
    public ResultBean<Receipts> selectByTableNameAndNo(String tableName, String no) {
        try {
            tableName = TableNameUtil.replaceTableName(tableName);
            Receipts receipts = receiptsMapper.selectByTableNameAndNo(tableName, no);
            return new ResultBean<>(receipts);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    // 查询，通过表名和内部编码来获取主子表数据
    @Override
    public ResultBean<List<MaterialConcrete>> selectAutocompleteInput(String tableName) {
        try {
            System.out.println(tableName);
            List<MaterialConcrete> material = receiptsMapper.selectAutocompleteInput();
            System.out.println(material);
            return new ResultBean<>(material);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultBean<>(400, "查询失败!");
        }
    }

    //创建boom材料清单
    public Object boomCreate( String orderId) {
        Map<String, Integer> needs = new HashMap<>();
        List<ReceiptsSub> receiptSubOrders = receiptsSubMapper.selectByNo(orderId, "order_receipt_sub");
        for (ReceiptsSub cur : receiptSubOrders) {
            System.out.println(cur);
            String name = cur.getSubJson().getString("homemadeName");
            int quantity = cur.getSubJson().getInteger("quantity");
            String bomName = cur.getSubJson().getString("bomName");
            List<Receipts> receiptsBom = receiptsMapper.selectByName(bomName, "bom_maintenance_receipt");
            List<ReceiptsSub> receiptSubBoms = receiptsSubMapper.selectByNo(receiptsBom.get(0).getNo(), "bom_maintenance_receipt_sub");
            findBom(needs, name, quantity,receiptSubBoms);
        }
        List<Material> productionPlans=new ArrayList<>();
        for (Map.Entry<String, Integer> need : needs.entrySet()) {
            System.out.println(need);
            Material material = new Material();
            material.setCategoryName(need.getKey());
            material.setUnit(need.getValue().toString());
            productionPlans.add(material);
        }
        return productionPlans;
    }

    private void findBom(Map<String, Integer> needs,  String name, int number ,List<ReceiptsSub> receiptSubBoms) {
        System.out.println(receiptSubBoms.size());
        for (ReceiptsSub receiptSubBom : receiptSubBoms) {
            System.out.println(receiptSubBom);
            String materialName = receiptSubBom.getSubJson().getString("materialName");
            Integer quantity = receiptSubBom.getSubJson().getInteger("materialNumber");
            if (needs.get(materialName) == null) {
                needs.put(materialName, quantity * number);
            } else {
                needs.put(materialName, quantity * number + needs.get(materialName));
            }
        }
    }
    //组合搜索
    @Override
    public ResultBean<List<Receipts>> searchRecord(String tableName, Receipts receipts, String queryCode) {
        try {
            receipts.setTableName(TableNameUtil.replaceTableName(tableName));
            receipts.setTableNameSub(receipts.getTableName() + "_sub");
            receipts.setQueryCode(queryCode);
            List<Receipts> receiptsList = receiptsMapper.searchRecord(receipts);
            return new ResultBean<>(receiptsList, 201, "查询成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultBean<>(400, "查询失败!");
        }
    }
}
